package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    /**
     * 获取验证码
     * @param user
     */
    @ApiOperation("获取验证码")
    @PostMapping("/sendMsg")
    public void checkCode(@RequestBody User user, HttpServletRequest request) {
        log.info("user = {}",user);

        // 1. 生成随机数
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        log.info("验证码 code = {}",code);
        // 2. 将验证码发送到手机上
//        SMSUtils.sendMessage("","",user.getPhone(),code);

        // 3. 将验证码存入session中
//        request.getSession().setAttribute(user.getPhone(),code);

        // 优化，将验证码，保存到Redis中
        redisTemplate.opsForValue().set(user.getPhone(), code.toString(), 5, TimeUnit.MINUTES);

    }

    /**
     * 用户登陆
     * @return
     */
    @ApiOperation("用户登陆")
    @PostMapping("/login")
    public R login(@RequestBody Map map,HttpServletRequest request) {
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        // 从Session中获取验证码
//        String codeInSession = request.getSession().getAttribute(phone).toString();

        // 优化，需要从Redis中获取验证码
        String codeIsRedis = redisTemplate.opsForValue().get(phone);

        // 1. 校验验证码是否正确
        if (codeIsRedis != null && codeIsRedis.equals(code)) {

            // 登陆成功，查询用户是否注册，如果没有注册
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(lambdaQueryWrapper);

            if (user == null) {
                // 表示用户没有注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);

                userService.save(user);
            }
            request.getSession().setAttribute("user",user.getId());
            // 销毁session中的验证码值
//            request.getSession().removeAttribute(phone);

            // 登陆成功，销毁Redis中的验证码
            redisTemplate.delete(phone);

            return R.success(user);
        }

        return R.error("登陆失败!");
    }


    /**
     * 退出登陆
     * @return
     */
    @ApiOperation("退出登陆")
    @PostMapping("/loginout")
    public R loginout(HttpServletRequest request) {

        // 删除session值
        request.getSession().invalidate();
        return R.success();

    }

}
